<?php
declare (strict_types=1);

namespace app\middleware;

use app\model\CommoditySpike;
use think\facade\Db;

class SpikeCheck
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        RedisLock('Spike_user_' . $request->user_id);
        if (empty($request->data['spike_id']) || !isset($request->data['spike_id'])) {
            return app('json')->json_error('参数错误');
        }
        $spike_id = intval($request->data['spike_id']);
        $address = Db::name('address')->where(['id' => $request->data['address_id']])->find();
        if (empty($address)) {
            return app('json')->json_error('收货地址不存在');
        }
        if ($address['user_id'] != $request->user_id) {
            return app('json')->json_error('收货地址信息异常');
        }
        //判断商品库存够不够
        //当天库存数量是否大于当天下单量订单数量
        $spike = app()->make(CommoditySpike::class)->where(['id' => $request->data['spike_id']])->find();
        if ($spike['spike_price'] < 1) {
            return app('json')->json_error('秒杀商品设置错误');
        }
        //--查看收货地址是否是偏远地区计算价格 保存order
        if ($request->user->integral < $spike['spike_price']) {
            return app('json')->json_error('余额不足');
        }
        if (!$spike) {
            return app('json')->json_error('秒杀商品不存在');
        }
        $user_queue_key = "Goods_" . $spike_id . "_User_" . date('Y-m-d', time());//当前商品队列的用户情况
        $goods_number_key = "Goods" . $spike_id . '_' . date('Y-m-d', time());//当前商品的库存队列
        //查看当前时间
        switch ($spike->spike_t_id) {
            case 1:
                $star_time = '10000';
                $end_time = '115959';
                break;
            case 2:
                $star_time = '120000';
                $end_time = '135959';
                break;
            case 3:
                $star_time = '140000';
                $end_time = '155959';
                break;
            case 4:
                $star_time = '160000';
                $end_time = '175959';
                break;
            default:
                return app('json')->json_error('秒杀商品有误');
        }
        $time = date('His');
        if ($time < $star_time || $time > $end_time) {
            return app('json')->json_error('当前商品的时间已经结束了哦~');
        }
        $goods_orders = Db::name('commodity_order_goods')->whereBetween('created_time', [DateTime()['t_s'], DateTime()['t_e']])->select()->toArray();
        $order_count = count($goods_orders);
        if ($spike->spike_num <= $order_count) {
            return app('json')->json_error('当前商品已经卖完！');
        }
        $request->data = ['user_queue_key' => $user_queue_key, 'goods_number_key' => $goods_number_key, 'spike' => $spike, 'address_id' => $request->data['address_id'], 'goods_msg' => $request->data['goods_msg']];
        return $next($request);
    }


}
